package app.server.project.main.service.db.dao.user;

import app.server.project.main.service.db.entity.user.UserWalletEntity;
import app.server.project.main.service.db.mapper.user.UserWalletMapper;
import app.server.project.main.service.service.upay.tron.constants.TxStatus;
import cn.hutool.core.util.IdUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Repository;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Objects;

@Repository
public class UserWalletDao extends ServiceImpl<UserWalletMapper, UserWalletEntity> {


    @Cacheable(key = "#userId+':'+#blockType", cacheNames = "app.server.project.main.service.db.dao.UserWalletDao.getWalletBy")
    public UserWalletEntity getWalletBy(long userId, int blockType) {
        var data = this.getOne(Wrappers.<UserWalletEntity>lambdaQuery()
                .eq(UserWalletEntity::getUserId, userId)
                .eq(UserWalletEntity::getBlockType, blockType));
        if (Objects.isNull(data)) {
            //缓存没有,就往库中写入一条数据
            data = UserWalletEntity.of(userId, IdUtil.getSnowflakeNextId());
        }
        data.setSynDb(true);
        return data;
    }


    @Cacheable(key = "#addressHuman+':'+#blockType", cacheNames = "app.server.project.main.service.db.dao.UserWalletDao.getWalletByAddress")
    public UserWalletEntity getWalletByAddress(String addressHuman, int blockType) {
        var data = this.getOne(Wrappers.<UserWalletEntity>lambdaQuery()
                .eq(UserWalletEntity::getAddressHuman, addressHuman)
                .eq(UserWalletEntity::getBlockType, blockType));
        if (Objects.isNull(data)) {
            //缓存没有,就往库中写入一条数据
            data = UserWalletEntity.Null();
        }
        data.setSynDb(true);
        return data;
    }

    @CachePut(key = "#wallet.addressHuman+':'+#wallet.blockType", cacheNames = "app.server.project.main.service.db.dao.UserWalletDao.getWalletByAddress")
    public UserWalletEntity updateWallet(UserWalletEntity wallet) {
        return wallet;
    }


    public List<UserWalletEntity> getFailTx() {
        var list = this.list(Wrappers.<UserWalletEntity>lambdaQuery().eq(UserWalletEntity::getActiveTxFlag, TxStatus.Fail));
        return list;
    }

    public void updateTxTime(UserWalletEntity wallet) {
        this.update(Wrappers.<UserWalletEntity>lambdaUpdate()
                .eq(UserWalletEntity::getId, wallet.getId())
                .set(UserWalletEntity::getLastTransferTime, LocalDateTime.now()));
    }


}
